package xyz.xwls.bootadmin.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import xyz.xwls.bootadmin.common.CommonResult;
import xyz.xwls.bootadmin.component.BaseController;
import xyz.xwls.bootadmin.sys.domain.User;
import xyz.xwls.bootadmin.sys.service.UserService;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author WZW
 * @date 2020/4/1
 */
@Api("账户相关")
@RestController
@Slf4j
public class AdminController extends BaseController {

    @Autowired
    private UserService userService;

    @Data
    static
    class LoginParam{
        private String username;
        private String password;
    }

    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query")
    })
    @PostMapping("/login")
    public CommonResult<String> login(@RequestBody LoginParam loginParam) {
        System.out.println("loginParam = " + loginParam);
        String token = userService.login(loginParam.username, loginParam.password);
        return CommonResult.success(token);
    }

    @Data
    static class LoginUser{
        private Long id;
        private String username;
        private String name;
        private Set<String> permissions;
    }

    @GetMapping("/info")
    public CommonResult<LoginUser> info(){
        LoginUser loginUser = new LoginUser();
        User user = getUser();
        loginUser.setId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setName(user.getName());
        Set<String> permissions = new LinkedHashSet<>();
        user.getAuthorities().forEach(grantedAuthority -> {
            permissions.add(grantedAuthority.getAuthority());
        });
        loginUser.setPermissions(permissions);
        return CommonResult.success(loginUser);
    }

    @GetMapping("/logout")
    public CommonResult<String> logout(){
        return CommonResult.success("退出成功");
    }

}
